import cv2
import random
import numpy as np
import matplotlib.pyplot as plt


def my_show(img, size=(2, 2)):
    plt.figure(figsize=size)
    plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    plt.show()


def image_crop():  # you code here
    img_ori = cv2.imread('lenna.jpg', 1)
    img_crop = img_ori[150:300, 100:300]
    my_show(img_crop)


def img_cooler(img, b_increase, r_decrease):
    B, G, R = cv2.split(img)  # 对通道进行分割，并对每个通道进行处理
    b_lim = 255 - b_increase
    B[B > b_lim] = 255
    B[B <= b_lim] = (b_increase + B[B <= b_lim]).astype(img.dtype)
    r_lim = r_decrease
    R[R < r_lim] = 0
    R[R >= r_lim] = (R[R >= r_lim] - r_decrease).astype(img.dtype)
    return cv2.merge((B, G, R))


def color_shift():  # you code here
    img_ori = cv2.imread('/Users/liguanghui/Documents/技术教程/开课吧/1.5 图像处理基础/CV第一次上课代码和数据-课后作业/lenna.jpg', 1)
    img_cool = img_cooler(img_ori, 50, 10)
    my_show(img_cool)


def rotation():  # you code here
    img = cv2.imread('/Users/liguanghui/Documents/技术教程/开课吧/1.5 图像处理基础/CV第一次上课代码和数据-课后作业/lenna.jpg', 1)
    cv2.imshow('src', img)
    imgInfo = img.shape
    height = imgInfo[0]
    width = imgInfo[1]
    deep = imgInfo[2]

    # 定义一个旋转矩阵
    matRotate = cv2.getRotationMatrix2D((height * 0.5, width * 0.5), 45, 0.7)  # mat rotate 1 center 2 angle 3 缩放系数
    dst = cv2.warpAffine(img, matRotate, (height, width))
    cv2.imshow('image', dst)
    cv2.waitKey(0)


def perspective_transform():  # you code here
    img = cv2.imread('lenna.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
    h, w = img.shape[:2]
    src = np.array([[0, 0], [w - 1, 0], [0, h - 1], [w - 1, h - 1]], np.float32)
    dst = np.array([[50, 50], [w / 3, 50], [50, h - 1], [w - 1, h - 1]], np.float32)
    P = cv2.getPerspectiveTransform(src, dst)  # 计算投影矩阵
    r = cv2.warpPerspective(img, P, (w, h), borderValue=125)
    cv2.imshow('img', img)
    cv2.imshow('warpPerspective', r)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == '__main__':
    image_crop()
    #color_shift()
    #rotation()
    #perspective_transform()